/**
 * 添加或者修改页面
 */
var TDispatchInfoDlg = {
    data: {
        mileageTraveled: ""
    }
};
var submit = 2
layui.use(['table', 'admin', 'ax','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var form = layui.form;

    laydate.render({
      elem: '#startTime'
        	,value:new Date()
    });

    laydate.render({
      elem: '#endTime'
        	,value:new Date()
    });

    /**
     * 调度单表管理
     */
    var TDispatch = {
        tableId: "tDispatchTable"
    };

    /**
     * 回传单表管理
     */
    var TransportReceipt = {
        tableId: "transportReceiptTable"
    };

    /**
     * 初始化表格的列
     */
    TDispatch.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键id'},
            {field: 'startDate', sort: true, title: '发车日期', style:'font-weight: 600;'},
            {field: 'returnTstate', sort: true, title: '回单状态', style:'font-weight: 600;',width: 140},
            {field: 'stateTb', sort: true, title: '提报状态', style: 'font-weight: 600;',
                templet: function (d) {
                    var str = "";
                    if (d.stateTb == '未提报') {
                        str += '<span style="color:#ff003b;font-weight: bold;">' + d.stateTb + '</span>'
                    } else if (d.stateTb == '已提报') {
                        str += '<span style="color:#19be6b;font-weight: bold;">' + d.stateTb + '</span>'
                    } else {
                        str += '<span style="font-weight: bold;">' + d.stateTb + '</span>'
                    }
                    return str
                }
            },
            {field: 'siji', sort: true, title: '司机', style:'font-weight: 600;',width: 100},
            {field: 'carnumber', sort: true, title: '车号', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'sijidianhua', sort: true, title: '电话', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'trainNumber', sort: true, title: '车次', style:'font-weight: 600;'},
            {field: 'fayunTimes', sort: true, title: '发运时间', style:'font-weight: 600;',width: 140},
            {field: 'returnTime', sort: true, title: '回单时间', style:'font-weight: 600;'},
            {field: 'stateTbTime', sort: true, title: '提报时间', style:'font-weight: 600;'},
            {field: 'mileageTraveled', sort: true, title: '测算里程', style:'font-weight: 600;'},
            {field: 'mileageTraveledYy', sort: true, title: '实际里程', style:'font-weight: 600;'},
            {field: 'remain', sort: true, title: '停留次数', style:'font-weight: 600;'},
            {field: 'dispatchNumber', sort: true, title: '运输单号', style:'font-weight: 600;',width: 180},
            {field: 'tstate', sort: true, title: '运输状态', style:'font-weight: 600;',},
            {field: 'chexing', sort: true, title: '车型', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'loadingType', sort: true, title: '装车方', style:'font-weight: 600;'},
            {field: 'loadingPersonnel', title: '装车人员', style:'color: #2b85e4;'},
            {field: 'zhunzailiang', sort: true, title: '准载体积', style:'font-weight: 600;'},
            {field: 'fulllv', sort: true, title: '满载率%', style:'font-weight: 600;', totalRowText: '合计：'},
            {field: 'zhuangzaiFileid', hide: true, title: '装载照片id'},
            {align: 'center', sort: true, toolbar: '#tableBar4', title: '装载照片'},
            {field: 'toovolume', sort: true, title: '总体积m3', style:'font-weight: 600;', totalRow: true},
            {field: 'tooNum', sort: true, title: '总数量', style:'font-weight: 600;', totalRow: true},
            {field: 'matrixingNumber', sort: true, title: '换算数量', style:'font-weight: 600;', totalRow: true},
            {field: 'toomoney', sort: true, title: '货值', style:'font-weight: 600;', totalRow: true},
            {field: 'chengyunfangshi', sort: true, title: '承运方式', style:'font-weight: 600;'},
            {field: 'chengyunleixing', sort: true, title: '承运类型', style:'font-weight: 600;'},
            {field: 'carrierName', sort: true, title: '承运商', style:'font-weight: 600;'},
            {field: 'lineName', sort: true, title: '线路', style:'font-weight: 600;'},
            {field: 'consultMoney', sort: true, title: '系统参考价￥', style:'font-weight: 600;',templet: '#consultMoneyTpl', totalRow: true},
            {field: 'money', sort: true, title: '付款金额', style:'font-weight: 600;', totalRow: true},
            {field: 'freightMoney', sort: true, title: '运费', style:'font-weight: 600;', totalRow: true},
            {field: 'loadingMoney', sort: true, title: '装车费', style:'font-weight: 600;', totalRow: true},
            {field: 'xiechefei', sort: true, title: '卸车费', style:'font-weight: 600;', totalRow: true},
            {field: 'payee', sort: true, title: '结算对象', style:'font-weight: 600;'},
            {field: 'dianduyuan', sort: true, title: '调度员', style:'font-weight: 600;'},
            {field: 'createTime', sort: true, title: '调度时间', style:'font-weight: 600;'},
            {field: 'examineName', sort: true, title: '审核人', style:'font-weight: 600;'},
            {field: 'examineTimes', sort: true, title: '审核时间', style:'font-weight: 600;'},
            {field: 'completeName', sort: true, title: '完成人', style:'font-weight: 600;'},
            {field: 'completeTimes', sort: true, title: '完成时间', style:'font-weight: 600;'},
            {field: 'operateName', sort: true, title: '项目', style:'font-weight: 600;'},
            {field: 'notes', sort: true, title: '备注', style:'font-weight: 600;'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    TDispatch.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['tstate'] = $("#tstate").val();
        queryData['stateTb'] = $("#stateTb").val();
        queryData['returnTstate'] = $("#returnTstate").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['carrierId'] = $("#carrierId").val();
        queryData['lineName'] = $("#lineName").val();
        queryData['carrierNames'] = $("#carrierNames").val();
        table.reload(TDispatch.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + TDispatch.tableId,
        url: Feng.ctxPath + '/tDispatch/list',
        page: true,
        limit: 240,
		limits:[60,120,240,360,480,600,2000,5000],
        height: 400,
        totalRow: true,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: ['filter', 'exports', 'print'],
        cellMinWidth: 100,
        cols: TDispatch.initColumn()
    });


    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        TDispatch.search();
    });

    //查询库区
    form.on('select(operateId)',function(){
        $("#carrierId").empty();
        $.ajax({
            url:Feng.ctxPath + '/basicCarrier/Querylist',
            dataType:"json",   //返回格式为json
            async: false,
            data:{"operateId":$("#operateId").val()},    //参数值
            type:"post",   //请求方式
            success:function(data){
                if(data.length>0){
                    var str = "<option value=''>选择承运商</option>";
                    $.each(data,function(key,value){
                        str += "<option value='"+value.id+"'>"+value.carrierName+"</option>";
                    });
                    $("#carrierId").html(str);
                }
            }
        });
        form.render('select');
    });

    // 导入
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: '【W6】已提报的运输单号',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/tDispatch/toimportExcel',
            end: function () {
                table.reload(TDispatch.tableId);
            }
        });
    });

    /**
     * 初始化表格的列
     */
    TransportReceipt.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键id'},
            {field: 'printNumHx', title: '零售打印发车单次数', style:'font-weight: 600;'},
            {field: 'stockPort', title: '备货口', style:'color: #2b85e4;'},
            {field: 'deliverys', title: ' 配送顺序', style:'color: #2b85e4;'},
            {field: 'getUnitid', hide: true, title: '卸货单位ID'},
            {field: 'getUnit', title: '单位', style:'background-color: #dbf1e1;font-weight: 600;', width: 140},
            {field: 'getLocation', title: '地址', style:'background-color: #dbf1e1;font-weight: 600;', width: 160},
            {field: 'getLocationid', hide: true, title: '卸货地址id'},
            {field: 'getPeople', hide: true, title: '联系人', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'getTel', hide: true, title: '联系电话', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'longitude', title: '经度', style:'font-weight: 600;'},
            {field: 'latitude', title: '纬度', style:'font-weight: 600;'},
            {field: 'kilometer', title: '公里数', style:'font-weight: 600;'},
            {field: 'num', sort: true, title: '数量'},
            {field: 'volume', title: '体积'},
            {field: 'sdtstate', sort: true, title: '送达状态', style:'font-weight: 600;'},
            {field: 'sdfileId', title: '电子签名',templet: '#sdpaymentProveTpl', event: 'sdpaymentProve'},
            {field: 'sdtime', sort: true, title: '送达时间'},
            {field: 'sdusername', title: '送达人员'},
            {field: 'tstate', sort: true, title: '回单状态', style:'font-weight: 600;'},
            {field: 'fileId', title: '回单',templet: '#paymentProveTpl', event: 'paymentProve'},
            {field: 'time', sort: true, title: '回传时间'},
            {field: 'username', title: '回传人员'},
        ]];
    };

    // 单击行事件
    table.on('row(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + TDispatch.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + TDispatch.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
		receipt(data);
    });
    
    function receipt(dataas){
    	var dispatchNumber;
    	if (dataas!=null) {
    		dispatchNumber = dataas.dispatchNumber;
		} else {
			dispatchNumber = 'nodata';
		}

        // 渲染表格
        var tableResult = table.render({
            elem: '#' + TransportReceipt.tableId,
            url: Feng.ctxPath + '/transportReceipt/list?dispatchNumber='+dispatchNumber,
            page: true,
            limit: 20,
            height: 390,
	        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
	        defaultToolbar: ['filter', 'exports', 'print'],
            cellMinWidth: 100,
            cols: TransportReceipt.initColumn()
        });

	    // 编辑单元格 事件
	    table.on('edit(' + TransportReceipt.tableId + ')', function (obj) {
	        var data = obj.data;//得到所在行所有键值
			var value = obj.value;//修改后的值
	        var field = obj.field;
			if(field == 'stockPort'){
		        var ajax = new $ax(Feng.ctxPath + "/transportReceipt/editStockPort?id="+data.id+"&stockPort="+value, function (data) {
		    		if (data.success) {
		                Feng.success("修改成功!");
					} else {
		                Feng.error("修改失败！"+data.message);
					}
		        }, function (data) {
		            Feng.error("修改失败!" + data.responseJSON.message + "!");
		        });
		        ajax.start();
			}
			if(field == 'deliverys'){
		        var ajax = new $ax(Feng.ctxPath + "/transportReceipt/editStockPort?id="+data.id+"&deliverys="+value, function (data) {
		    		if (data.success) {
		                Feng.success("修改成功!");
					} else {
		                Feng.error("修改失败！"+data.message);
					}
		        }, function (data) {
		            Feng.error("修改失败!" + data.responseJSON.message + "!");
		        });
		        ajax.start();
			}
	    });

        // 工具条点击事件
        table.on('tool(' + TransportReceipt.tableId + ')', function (obj) {
            var data = obj.data;
            if (obj.event === 'paymentProve') {
      	    	//构建图像数组
	      		var items = [];
	        	if (data.fileId!='') {
            		var obj = {};
            		obj.src = '/transportReceipt/show?fileId=' + data.fileId;
            		obj.title = '预览图片';
            		items.push(obj)
	    	      	//定义选项（如果需要）
	    	      	var options = {
	    	      	    index: 0 // 此选项表示您将从第一张图片开始
	    	      	};
	    	      	//初始化插件
	    	      	var viewer = new PhotoViewer(items, options);
				} else {
	                Feng.info("暂无照片!");
				}
            } else if (obj.event === 'sdpaymentProve') {
      	    	//构建图像数组
	      		var items = [];
	        	if (data.sdfileId!='') {
            		var obj = {};
            		obj.src = '/transportReceipt/show?fileId=' + data.sdfileId;
            		obj.title = '预览图片';
            		items.push(obj)
	    	      	//定义选项（如果需要）
	    	      	var options = {
	    	      	    index: 0 // 此选项表示您将从第一张图片开始
	    	      	};
	    	      	//初始化插件
	    	      	var viewer = new PhotoViewer(items, options);
				} else {
	                Feng.info("暂无照片!");
				}
            } else if (obj.event === 'huowu'){
                layer.open({
                    type: 2,
                    title: '货物明细',
                    area: ['1100px', '500px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportDispatch?dispatchNumber=' + data.dispatchNumber+'&getUnitid='+data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } else if (obj.event === 'gaidizhi') {
	            layer.open({
	                type: 2,
	                title: '修改地址',
	                area: ['1000px', '800px'],
	                content: Feng.ctxPath + '/orderTransportDispatch/toGaidizhi?id=' + data.getLocationid + "&setLocationId=" + data.setLocationId,
	                end: function () {
		                receipt(dataas);
	                }
	            });
	    	} else if (obj.event === 'print'){
                layer.open({
                    type: 2,
                    title: '打印送货单',
                    area: ['750px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/print?dispatchNumber=' + data.dispatchNumber+'&getUnitid='+data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } else if (obj.event === 'printTy'){
                layer.open({
                    type: 2,
                    title: '打印托运单',
                	area: ['990px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/printTy?dispatchNumber=' + data.dispatchNumber+'&getUnitid='+data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } else if (obj.event === 'songda'){
		        var operation = function () {
		            var ajax = new $ax(Feng.ctxPath + "/tDispatch/editsongda", function (data) {
			            if (data.success) {
			                Feng.success("操作成功!");
			                receipt(dataas);
						} else {
			                Feng.error("修改失败！"+data.message);
						}
		            }, function (data) {
		                Feng.error("操作失败!" + data.responseJSON.message + "!");
		                receipt(dataas);
		            });
		            ajax.set("id", data.id);
		            ajax.set("dispatchNumber", data.dispatchNumber);
		            ajax.set("getUnitid", data.getUnitid);
		            ajax.set("getUnit", data.getUnit);
		            ajax.set("getLocationid", data.getLocationid);
		            ajax.set("getLocation", data.getLocation);
		            ajax.start();
		        };
		        Feng.confirm("确定送达吗?", operation);
            } else if (obj.event === 'qianshou'){
                layer.open({
                    type: 2,
                    title: '签收上传回单',
                    area: ['750px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportReceipt/edit_uploads?id=' + data.id,
	                end: function () {
		                receipt(dataas);
	                }
                });
            } else if (obj.event === 'qianshou_update'){
                layer.open({
                    type: 2,
                    title: '修改回单',
                    area: ['750px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportReceipt/edit_uploads?id=' + data.id,
	                end: function () {
		                receipt(dataas);
	                }
                });
            } else if (obj.event === 'printHx'){
                layer.open({
                    type: 2,
                    title: '打印零售发货单',
                	area: ['990px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/printHx?dispatchNumber=' + data.dispatchNumber + '&getLocationid=' + data.getLocationid+ '&startDate=' + dataas.startDate,
                });
            }
        });
    };
});
